import { Service } from 'egg';
import { UserProps } from '../model/user'

interface GiteeUserInfoData {
  id: BigInteger;
  name: string;
  email: string;
  events_url: string
}

export default class UserService extends Service {
  public async createByEmail(payload: UserProps) {
    const { ctx } = this;
    const { username, password } = payload;
    // 密码进行加密
    const hash = await ctx.genHash(password);
    const userCreateData: Partial<UserProps> = {
      username,
      password: hash,
      email: username
    }
    return ctx.model.User.create(userCreateData)
  }
  async findById(id: string) {
    return this.ctx.model.User.findById(id)
  }
  async findByUsername(username: string) {
    return this.ctx.model.User.findOne({ username })
  }
  async loginByCellPhone() {
    const { ctx, app } = this;
    // 先进行用户是否存在
    const { phoneNumber } = ctx.request.body;
    const userData = await this.findByUsername(phoneNumber);
    if (userData) {
      const { username, _id } = userData
      const token = app.jwt.sign({ username, _id }, app.config.jwt.secret, { expiresIn: 60 * 60 })
      return token
    }
    // 没有用户直接新建一个用户
    // const hash = await ctx.genHash('12345678');// 初始密码
    const userCreateData: Partial<UserProps> = {
      username: phoneNumber,
      // password: hash,
      phoneNumber,
      loginType: 'cellphone',
      nickName: `spiritos-${phoneNumber.slice(-4)}`
    }
    const newUser = await ctx.model.User.create(userCreateData)
    const token = app.jwt.sign({ username: newUser.username, _id: newUser._id }, app.config.jwt.secret, { expiresIn: 60 * 60 })
    return token
  }
  async getAcessToken(code: string) {
    const { ctx, app } = this;
    const { authURL, cid, secret, redirectURL } = app.config.giteeOauthConfig;
    const { data } = await ctx.curl(authURL, {
      method: 'POST',
      contentType: 'json',
      dataType: 'json',
      data: {
        code,
        client_id: cid,
        redirect_uri: redirectURL,
        client_secret: secret
      }
    })

    return data.access_token

  }

  async getUserDataByGitee(accessToken: string) {
    const { ctx, app } = this;
    const { giteeUserInfoApi } = app.config.giteeOauthConfig;
    const { data } = await ctx.curl<GiteeUserInfoData>(`${giteeUserInfoApi}?access_token=${accessToken}`, {
      dataType: 'json',
    });
    // 获得授权后的用户信息，存储到数据库
    const { id, name, email, events_url } = data
    // 判断用户是否存在
    const userData = await this.findByUsername(`gitee${id}`);
    if (userData) {
      // 用户存在直接登录
      const { username, _id } = userData
      const token = app.jwt.sign({ username, _id }, app.config.jwt.secret, { expiresIn: 60 * 60 })
      return token
    }
    // 不存在创建用户
    const userCreateData: Partial<UserProps> = {
      username: `gitee${id}`,
      oauthType: 'gitee',
      loginType: 'oauth',
      nickName: name,
      email,
      picture: events_url
    }
    const newUser = await ctx.model.User.create(userCreateData)
    const token = app.jwt.sign({ username: newUser.username, _id: newUser._id }, app.config.jwt.secret, { expiresIn: 60 * 60 })
    return token
  }

  async loginByGitee(code: string) {
    const accessToken = await this.getAcessToken(code);
    const user = await this.getUserDataByGitee(accessToken);
    return user
  }
}
